<template>
  <div class="case">
    <na-table :datas.sync="tableData" :searchObj.sync="search" @updateDatas="getAllSuppliers" @newAdd="newAddClick">
    </na-table>
    <!-- 新建供应商   -->
    <el-dialog title="新建供应商" :visible.sync="isAddSuppliers" :close-on-click-modal="false" custom-class="comDialog"
      width="40%" @close="closeDialog">
      <div class="dialogDody">
        <el-form ref="supplierForm" :model="supplierForm" :rules="rules" label-width="95px" class="dialogForm">
          <el-form-item label="供应商编号">
            <el-input v-model="supplierForm.supplierNumber" placeholder="系统自动生成" size="mini" disabled />
          </el-form-item>
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input v-model="supplierForm.supplierName" placeholder="供应商名称" size="mini" />
          </el-form-item>
          <el-form-item label="供应商类型" prop="supplierType">
            <el-select
                        filterable v-model="supplierForm.supplierType" filterable placeholder="请选择供应商类型" size="mini">
              <el-option v-for="item in supplierTypes" :key="item.dicValueID" :label="item.displayValue"
                :value="item.dicValueCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="发票类型" prop="invoiceType">
            <el-select
                        filterable v-model="supplierForm.invoiceType" filterable placeholder="请选择发票类型" size="mini">
              <el-option label="普通发票" :value="1" />
              <el-option label="专用发票" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="税率" prop="taxRate">
            <el-input  v-model.number="supplierForm.taxRate" placeholder="请输入税率" size="mini" >
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
          <el-form-item label="税号" prop="dutyParagraph">
            <el-input v-model="supplierForm.dutyParagraph" placeholder="请输入税号" size="mini" />
          </el-form-item>
          <el-form-item label="单位地址" prop="companyAddress">
            <el-input v-model="supplierForm.companyAddress" placeholder="请输入单位地址" size="mini" />
          </el-form-item>
          <el-form-item label="开户电话" prop="accountOpeningTelephone">
            <el-input v-model="supplierForm.accountOpeningTelephone" placeholder="请输入开户电话" size="mini" />
          </el-form-item>
          <el-form-item label="银行账号" prop="bankAccount">
            <el-input v-model="supplierForm.bankAccount" placeholder="请输入银行账号" size="mini" />
          </el-form-item>
          <el-form-item label="开户银行" prop="bankAddress">
            <el-input v-model="supplierForm.bankAddress" placeholder="请输入开户银行" size="mini" />
          </el-form-item>
          <el-form-item label="结算方式" prop="settlementWay">
            <el-select
                        filterable v-model="supplierForm.settlementWay" filterable placeholder="请输入仓库名称" size="mini">
              <el-option v-for="item in wayDataLists" :key="item.dicValueID" :label="item.displayValue"
                :value="item.dicValueCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="supplierForm.contactPerson" placeholder="请输入联系人" size="mini" />
          </el-form-item>
          <el-form-item label="联系电话" prop="contactMobile">
            <el-input v-model="supplierForm.contactMobile" placeholder="请输入联系电话" size="mini" />
          </el-form-item>
          <el-form-item label="供应商电话">
            <el-input v-model="supplierForm.supplierTel" placeholder="请输入供应商电话" size="mini" />
          </el-form-item>
          <el-form-item label="供应商地址">
            <el-cascader v-model="supplierForm.site" size="mini" :options="address"
              :props="{label:'areaName',value:'areaCode'}" @change="areaChange" />
          </el-form-item>
          <el-form-item label="" class="mt5">
            <el-input v-model="supplierForm.supplierAddress" type="textarea" placeholder="请输入内容" size="mini" />
          </el-form-item>
          <el-form-item label="备注" class="mt12">
            <el-input v-model="supplierForm.supplierRemark" type="textarea" placeholder="请输入内容" size="mini" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isAddSuppliers=false">取 消</el-button>
        <el-button v-loading="addLoading" :disabled="addLoading" element-loading-spinner="el-icon-loading"
          type="primary" size="mini" @click="addSave">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑供应商   -->
    <el-dialog :title="modelTitle+'供应商'" :visible.sync="isEditSuppliers" :close-on-click-modal="false"
      custom-class="comDialog" width="40%" @close="closeDialog">
      <div class="dialogDody">
        <el-form ref="editSupplierForm" :model="supplierForm" :rules="rules" label-width="95px" class="dialogForm">
          <el-form-item label="供应商编号">
            <el-input v-model="supplierForm.supplierNumber" placeholder="系统自动生成" size="mini" disabled />
          </el-form-item>
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input v-model="supplierForm.supplierName" placeholder="供应商名称" size="mini" />
          </el-form-item>
          <el-form-item label="供应商类型" prop="supplierType">
            <el-select
                        filterable v-model="supplierForm.supplierType" filterable placeholder="请选择供应商类型" size="mini">
              <el-option v-for="item in supplierTypes" :key="item.dicValueID" :label="item.displayValue"
                :value="item.dicValueCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="发票类型" prop="invoiceType">
            <el-select
                        filterable v-model="supplierForm.invoiceType" filterable placeholder="请选择发票类型" size="mini">
              <el-option label="普通发票" :value="1" />
              <el-option label="专用发票" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="税率" prop="taxRate">
            <el-input  v-model.number="supplierForm.taxRate" placeholder="请输入税率" size="mini" >
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
          <el-form-item label="税号" prop="dutyParagraph">
            <el-input v-model="supplierForm.dutyParagraph" placeholder="请输入税号" size="mini" />
          </el-form-item>
          <el-form-item label="单位地址" prop="companyAddress">
            <el-input v-model="supplierForm.companyAddress" placeholder="请输入单位地址" size="mini" />
          </el-form-item>
          <el-form-item label="开户电话" prop="accountOpeningTelephone">
            <el-input v-model="supplierForm.accountOpeningTelephone" placeholder="请输入开户电话" size="mini" />
          </el-form-item>
          <el-form-item label="银行账号" prop="bankAccount">
            <el-input v-model="supplierForm.bankAccount" placeholder="请输入银行账号" size="mini" />
          </el-form-item>
          <el-form-item label="开户银行" prop="bankAddress">
            <el-input v-model="supplierForm.bankAddress" placeholder="请输入开户银行" size="mini" />
          </el-form-item>
          <el-form-item label="结算方式" prop="settlementWay">
            <el-select
                        filterable v-model="supplierForm.settlementWay" filterable placeholder="请输入仓库名称" size="mini">
              <el-option v-for="item in wayDataLists" :key="item.dicValueID" :label="item.displayValue"
                :value="item.dicValueCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="supplierForm.contactPerson" placeholder="请输入联系人" size="mini" />
          </el-form-item>
          <el-form-item label="联系电话" prop="contactMobile">
            <el-input v-model="supplierForm.contactMobile" placeholder="请输入联系电话" size="mini" />
          </el-form-item>
          <el-form-item label="供应商电话">
            <el-input v-model="supplierForm.supplierTel" placeholder="请输入供应商电话" size="mini" />
          </el-form-item>
          <el-form-item label="供应商地址">
            <el-cascader v-model="supplierForm.site" size="mini" :options="address"
              :props="{label:'areaName',value:'areaCode'}" @change="areaChange" />
          </el-form-item>
          <el-form-item label="" class="mt5">
            <el-input v-model="supplierForm.supplierAddress" type="textarea" placeholder="请输入内容" size="mini" />
          </el-form-item>
          <el-form-item label="备注" class="mt12">
            <el-input v-model="supplierForm.supplierRemark" type="textarea" placeholder="请输入内容" size="mini" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isEditSuppliers=false">取 消</el-button>
        <el-button v-loading="addLoading" :disabled="addLoading" element-loading-spinner="el-icon-loading"
          type="primary" size="mini" @click="editSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {
    arraySort
  } from '@/utils'
  import naTable from "@/components/naTable";
  export default {
    name: 'Supplier',
    components: {
      naTable
    },
    data() {
      var checkTel = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('电话号码不能为空'))
        }
        setTimeout(() => {
          if (!Number.isInteger(+value)) {
            callback(new Error('请输入数字'))
          } else {
            if (/^1[3-9]\d{9}$/.test(value)) {
              callback()
            } else {
              callback(new Error('电话号码格式不正确'))
            }
          }
        }, 300)
      }
      return {
        searchLoading: false, // 搜索加载效果
        isAddSuppliers: false, // 新建弹框是否开启
        tabLoading: false, // 表格数据加载
        addLoading: false, // 新建供应商加载效果
        modelTitle: '',
        isEditSuppliers: false, // 编辑弹框是否开启
        // 供应商搜索条件
        search: {
          QueryDataBaseFiled: '',
          pageIndex: 1,
          pageSize: 30,
          likeWords: '',
          supplierType: '',
          supplierNature: '',
          supplierState: -1
        },
        suppTotale: 0, // 供应商总条数
        allSuppliers: [], // 供应商表格数据
        tableHead: [],
        address: [], // 地区联动数据
        tableHeight: null, // 表格最大高度
        operations: [
          [{
            text: '修改',
            key: 'modify'
          }],
          [{
            text: '启用',
            key: 'enable'
          }],
          [{
            text: '删除',
            key: 'delete'
          }]
        ], // 表格操作
        supplierForm: {
          supplierCode: '',
          supplierName: '',
          supplierType: '',
          settlementWay: '',
          contactPerson: '',
          contactMobile: '',
          supplierTel: '',
          supplierAddress: '',
          supplierRemark: '',
          site: '',
          province: '',
          city: '',
          country: ''
        },
        supplierTypes: [], // 供应商类型
        wayDataLists: [], // 结算方式
        isEnabled: null,
        rules: {
          supplierName: [{
            required: true,
            message: '请输入供应商名称',
            trigger: 'blur'
          }],
          supplierType: [{
            required: true,
            message: '请选择供应商类型',
            trigger: 'blur'
          }],
          settlementWay: [{
            required: true,
            message: '请选择结算方式',
            trigger: 'blur'
          }],
          contactPerson: [{
            required: true,
            message: '请输入联系人',
            trigger: 'blur'
          }],
          contactMobile: [{
            validator: checkTel,
            required: true,
            trigger: 'blur'
          }]
        },

        tableData: {
          headId: 'head', //表头列显隐组件所需ID-避免多个页面id重复问题
          tableId: 'supplierID', //表格列表key,也就是一条数据的唯一标识
          senior: false, //高级搜索是否显示
          disableWord: '', //是否禁用显示的字段
          disableStatus: '', //判断未禁用的状态值
          refresh: true, //刷新按钮
          addPermission: 'MenuCode5-10-2-1', //新建按钮权限
          statusList: [], //状态筛选条件列表
          statusWord: '', //状态筛选的字段
          showSum: true, //显示合计
          //表格按钮
          operationBtn: [{
              title: '修改',
              methodsName: 'modifyClick',
              permission:"MenuCode5-10-2-2",
            },
            {
              title: '删除',
              methodsName: 'deleteSupplier',
              permission:"MenuCode5-10-2-3",
            }
          ],
          //表格内容
          tbody: [],
          //表格表头
          thead: [],
        },
      }
    },
    created() {
      // 查询全部供应商
      this.getAllSuppliers()
      // 供应商表格得表头
      this.getTableHead()
      // 供应商类型
      this.getSupplierType()
      // 地区联动数据
      this.getArea()
      // 结算方式
      this.getWayList()
    },
    mounted() {},
    methods: {
      newAddClick() {
        this.isAddSuppliers = true;
        this.modelTitle = '新建'
      },
      // 保存新建供应商
      addSave() {
        const parmas = this.supplierForm
        this.$refs.supplierForm.validate((valid) => {
          if (valid) {
            this.addLoading = true
            this.$api.warehouse.AddSupplier(parmas).then(() => {
              this.addLoading = false
              this.isAddSuppliers = false
              // 查询全部供应商
              this.getAllSuppliers()
              this.$message({
                message: '新建成功',
                type: 'success'
              })
            }).catch(() => {
              this.addLoading = false
            })
          }
        })
      },
      // 保存编辑供应商
      editSave() {
        const parmas = this.supplierForm
        this.$refs.editSupplierForm.validate((valid) => {
          if (valid) {
            this.addLoading = true
            this.$api.warehouse.UpdateSupplier(parmas).then(() => {
              this.addLoading = false
              this.isEditSuppliers = false
              // 查询全部供应商
              this.getAllSuppliers()
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
            }).catch(() => {
              this.addLoading = false
            })
          }
        })
      },
      // 供应商详情
      getInfo(id) {
        const parmas = {
          queryBy: 1,
          queryValue: id.toString()
        }
        this.$api.warehouse.GetSingleSupplier(parmas).then(res => {
          if(!res.invoiceType){
            res.invoiceType = ''
          }
          this.supplierForm = res
          const arry = []
          arry.push(res.province)
          arry.push(res.city)
          arry.push(res.country)
          this.supplierForm.site = arry
        })
      },
      // 删除供应商
      deleteSupplier(data) {
        const parmas = {
          entityID: data.supplierID
        }
        this.$confirm('确定删除该供应商, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.warehouse.DeleteSupplier(parmas).then(() => {
            this.getAllSuppliers()
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          })
        })
      },
      // 设置供应商状态
      setSupplierSate(id) {
        const parmas = {
          supplierID: id,
          isDisabled: this.isEnabled
        }
        this.$confirm('确定启用/禁用, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.warehouse.ExcuteSupplier(parmas).then(() => {
            this.getAllSuppliers()
            this.$message({
              message: '设置成功',
              type: 'success'
            })
          })
        })
      },
      // 启用/禁用设置
      enableClick(data) {
        this.isEnabled = Boolean(data.isEnabled)
        this.setSupplierSate(data.supplierID)
      },
      // 修改
      modifyClick(data) {
        this.modelTitle = '修改'
        this.isEditSuppliers = true
        this.getInfo(data.supplierID)
      },

      // 供应商类型
      getSupplierType() {
        this.$api.common.GetSupplierTypeDataList().then(res => {
          this.supplierTypes = res
        })
      },
      // 结算方式
      getWayList() {
        this.$api.common.GetSettlementWayDataList().then(res => {
          this.wayDataLists = res
        })
      },
      // 合计方法
      getSummaries(param) {
        const {
          columns,
          data
        } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          if (column.property === 'goodsCount' || column.property === 'purchaseSumAmount' || column.property ===
            'paiedSumAmount' || column.property === 'waitPaySumAmount') {
            const values = data.map(item => Number(item[column.property]))
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] = sums[index]++
            } else {
              sums[index] = ' '
            }
          }
        })

        return sums
      },
      // 地区联动数据
      getArea() {
        this.$api.common.GetTreeAreaDataList().then(res => {
          this.address = res
        })
      },
      // 选择地址
      areaChange(val) {
        this.supplierForm.province = val ? val[0] : ''
        this.supplierForm.city = val ? val[1] : ''
        this.supplierForm.country = val ? val[2] : ''
      },
      // 保存表头样式变化
      saveHead(newArray) {
        const parmas = newArray
        setTimeout(() => {
          this.$api.common.saveTableStyle(parmas).then(() => {})
        }, 300)
      },
      // 保存表头列宽度
      surverWidth(newWidth, oldWidth, column) {
        setTimeout(() => {
          const heads = [...this.tableHead]
          heads.forEach(item => {
            if (item.columnCode === column.property) {
              item.columnWidth = column.width
              return
            }
          })
          this.saveHead(heads)
        }, 100)
      },
      // 获取供应商表格表头
      getTableHead() {
        const parmas = {
          tableCode: this.$config.supplierlist
        }
        this.$api.common.getAllTableHead(parmas).then(res => {
          res.sort(arraySort('columnSort'))
          this.tableData.thead = res
        })
      },
      // 查血全部供应商
      getAllSuppliers() {
        const parmas = this.search
        this.$api.warehouse.GetMatchPageSuppliers(parmas).then(res => {
          this.tableData.tbody = res.list;
          this.search.total = res.totalCount;
        })
      },
      // 关闭弹框事件
      closeDialog() {
        // 关闭弹框的时候清空数据
        if (this.$refs.supplierForm) {
          this.$refs.supplierForm.resetFields()
        }
        if (this.$refs.editSupplierForm) {
          this.$refs.editSupplierForm.resetFields()
        }
        this.supplierForm = this.$options.data().supplierForm
        this.wareShowper = '' // 清空管理员展示字段内容
      }
    }
  }

</script>
<style lang="scss" scoped>
</style>
